﻿using UnityEngine;

namespace Jinndev {

    /// <summary>
    /// UI跟随3D物体
    /// </summary>
    public class UIFollow3D : MonoBehaviour {

        public Camera targetCamera;
        public Transform target;
        public float uiScale = 1;
        public bool limitInScreen;
        public Vector2 screenPadding;

        private RectTransform rectTransform;
        //private Vector2 screenSize;

        private void Awake() {
            rectTransform = GetComponent<RectTransform>();
            //screenSize = CommonUtil.GetUIScreenSize(Const.ReferenceResolution);
        }

        private void Update() {
            SyncPosition();
        }

        public void SyncPosition() {
            if (target != null) {
                Camera camera = targetCamera;
                if (camera == null) {
                    camera = Camera.main;
                }
                Vector3 screenPoint = camera.WorldToScreenPoint(target.position);
                if (limitInScreen) {
                    screenPoint.x = Mathf.Clamp(screenPoint.x, screenPadding.x, Screen.width - screenPadding.x);
                    screenPoint.y = Mathf.Clamp(screenPoint.y, screenPadding.y, Screen.height - screenPadding.y);
                }
                Vector2 anchoredPosition = CommonUtil.ScreenPointToAnchoredPosition(screenPoint, uiScale);
                rectTransform.anchoredPosition = anchoredPosition;
            }
        }

    }

}
